import os
from django.conf import Settings, SettingsReference
from django.http import QueryDict
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
import ipaddress
from ImageModule.utils.customstorage import CustomStorage

from SystemConfiguration.models import ImagePath, InputSourceNetworkStream, InputSourceType, InputSourceUSB, VideoPath
from SystemConfiguration.serializers import InputSourceTypeSerializer, InputSourceUSBSerializer, InputSourceNetworkStreamSerializer, VideoPathSerializer, ImagePathSerializer
from airport_logistics_backend import settings
# Create your views here.
# from django.http import JsonResponse

class InputSourceViewSet(viewsets.ModelViewSet):

    # 用一个视图集替代ArticleList和ArticleDetail两个视图
    queryset_inputsource = InputSourceType.objects.all()
    serializer_class_inputsource = InputSourceTypeSerializer
    queryset_USB = InputSourceUSB.objects.all()
    serializer_class_USB = InputSourceUSBSerializer
    queryset_networkstream = InputSourceNetworkStream.objects.all()
    serializer_class_networkstream = InputSourceNetworkStreamSerializer
    
    def is_valid_ip(self, ip_str):
        try:
            ipaddress.ip_address(ip_str)
            return True
        except ValueError:
            return False
    
    # POST 
    def create(self, request):
        data_type = request.data['type']
        data_inputsource = QueryDict(mutable=True)
        data_inputsource['type'] = request.data['type']
        
        # usb设备
        if(data_type == '1'):
            fields_to_keep = ['usbnumber']
            data_USB = {key: request.data[key] for key in fields_to_keep if key in request.data}
            serializer_USB = InputSourceUSBSerializer(data=data_USB)
            if serializer_USB.is_valid():
                instance = serializer_USB.save()
                id = InputSourceUSBSerializer(instance).data['id']
            else:
                # 数据验证失败，打印错误信息
                print("Validation failed:", serializer_USB.errors)

                # 可以进一步处理错误信息，例如：
                for field, errors in serializer_USB.errors.items():
                    for error in errors:
                        print(f"Error in field '{field}': {error}")
            data_inputsource['fk'] = id
            serializer_inputsource = InputSourceTypeSerializer(data=data_inputsource)
            if serializer_inputsource.is_valid():
                instance = serializer_inputsource.save()
                return Response({'message': '新建usb成功'}, status=200)
            else:
                # 数据验证失败，打印错误信息
                print("Validation failed:", serializer_inputsource.errors)

                # 可以进一步处理错误信息，例如：
                for field, errors in serializer_inputsource.errors.items():
                    for error in errors:
                        print(f"Error in field '{field}': {error}")

        # 网络流
        elif(data_type == '2'):
            fields_to_keep = ['ip', 'port']
            data_NetworkStream = {key: request.data[key] for key in fields_to_keep if key in request.data}
            if(self.is_valid_ip(data_NetworkStream['ip']) == False):
                return Response('ip地址不符合规范', status=400)
            serializer_NetworkStream = InputSourceNetworkStreamSerializer(data=data_NetworkStream)
            if serializer_NetworkStream.is_valid():
                instance = serializer_NetworkStream.save()
                id = InputSourceNetworkStreamSerializer(instance).data['id']
                
            data_inputsource['fk'] = id
            serializer_inputsource = InputSourceTypeSerializer(data=data_inputsource)
            if serializer_inputsource.is_valid():
                instance = serializer_inputsource.save()
                return Response({'message': '新建图片成功'}, status=200)
        
        return Response(data_inputsource.errors, status=400)
    


    # GET
    # def list(self, request, *args, **kwargs):
    #     queryset = self.get_queryset()
    #     serializer = self.get_serializer(queryset, many=True)
    #     print(serializer)
    #     return Response(serializer.data,status=200)   

    # def get_queryset(self):
    #     queryset = Imagefile.objects.all()
    #     name = self.request.query_params.get('name')
    #     date = self.request.query_params.get('date')
    #     type = self.request.query_params.get('type')

    #     if name:
    #         queryset = queryset.filter(name__icontains=name)
    #     if date:
    #         queryset = queryset.filter(date=date)
    #     if type:
    #         queryset = queryset.filter(type__icontains=type)

    #     return queryset

class videoPathViewSet(viewsets.ModelViewSet):
    # 用一个视图集替代ArticleList和ArticleDetail两个视图
    queryset = VideoPath.objects.all()
    serializer_class = VideoPathSerializer

    #POST
    def create(self, request):
        # request.data['size'] = request.FILES['video'].size
        # request.data['media_root'] = settings.CUSTOM_STORAGE_LOCATION
        data_videopath = QueryDict(mutable=True)
        data_videopath['path'] = request.query_params.get('path')
        serializer = VideoPathSerializer(data=data_videopath)
        if serializer.is_valid():
            instance = serializer.save()
            if not os.path.exists(data_videopath['path']):
                os.makedirs(data_videopath['path'])
            # storage.location = data_videopath['path']
            settings.CUSTOM_STORAGE_LOCATION = data_videopath['path']
            storage = CustomStorage(location = settings.CUSTOM_STORAGE_LOCATION,base_url='')
            storage.set_location(new_location = settings.CUSTOM_STORAGE_LOCATION)
            return Response({'message': '更改路径成功'}, status=200)
        else:
            # 数据验证失败，打印错误信息
            print("Validation failed:", serializer.errors)

            # 可以进一步处理错误信息，例如：
            for field, errors in serializer.errors.items():
                for error in errors:
                    print(f"Error in field '{field}': {error}")
        return Response(serializer.errors, status=400)
    
    #GET
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        # latest_entry = VideoPath.objects.order_by('-id').first().path
        # serializer = self.get_serializer(queryset, many=True)
            # 获取id最新的一条记录
        latest_entry = VideoPath.objects.all().order_by('-id').first()

        # 使用序列化器
        serializer = self.get_serializer(latest_entry)
        print(serializer)
        return Response(serializer.data,status=200)   
    
class imagePathViewSet(viewsets.ModelViewSet):
     # 用一个视图集替代ArticleList和ArticleDetail两个视图
    queryset = ImagePath.objects.all()
    serializer_class = ImagePathSerializer

    #POST
    def create(self, request):
        # request.data['size'] = request.FILES['video'].size
        # request.data['media_root'] = settings.CUSTOM_STORAGE_LOCATION
        data_iamgepath = QueryDict(mutable=True)
        data_iamgepath['path'] = request.query_params.get('path')
        serializer = ImagePathSerializer(data=data_iamgepath)
        if serializer.is_valid():
            instance = serializer.save()
            if not os.path.exists(data_iamgepath['path']):
                os.makedirs(data_iamgepath['path'])
            # storage.location = data_videopath['path']
            settings.CUSTOM_STORAGE_LOCATION_IMAGE = data_iamgepath['path']
            # storage = CustomStorage(location = settings.CUSTOM_STORAGE_LOCATION_IMAGE,base_url='')
            # storage.set_location(new_location = settings.CUSTOM_STORAGE_LOCATION_IMAGE)
            return Response({'message': '更改路径成功'}, status=200)
        else:
            # 数据验证失败，打印错误信息
            print("Validation failed:", serializer.errors)

            # 可以进一步处理错误信息，例如：
            for field, errors in serializer.errors.items():
                for error in errors:
                    print(f"Error in field '{field}': {error}")
        return Response(serializer.errors, status=400)
    
    #GET
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        # latest_entry = VideoPath.objects.order_by('-id').first().path
        # serializer = self.get_serializer(queryset, many=True)
            # 获取id最新的一条记录
        latest_entry = ImagePath.objects.all().order_by('-id').first()

        # 使用序列化器
        serializer = self.get_serializer(latest_entry)
        print(serializer)
        return Response(serializer.data,status=200)   